//
//  FYUserAccountViewModel.swift
//  dugeweibo
//
//  Created by pelesys on 16/8/6.
//  Copyright © 2016年 杜方宜. All rights reserved.
//

import UIKit
import AFNetworking
//ViewModel 将一些业务逻辑封装到 这个类里  让这个隔离的更加好
class FYUserAccountViewModel: NSObject {
    //增加userAccount属性
    var account : FYUserAccount?
       //增加用户是否登录的属性
    var userLogin : Bool {
     return account?.access_token != nil
    
    }
    var token :String?{
        return account?.access_token
    }
    
    var userName : String?{
        return account?.name
    }
    //用户头像
    var headURL:NSURL?{
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    //在init方法中获取 用户账户
    override init() {
        account = FYUserAccount.loadAccout()
    }

    
    //加载用户token
    func loadAccessToken(code:String,finished:@escaping (_ error:NSError?)->()){
        let urlString = tockenURL
        //参数字典
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        //failed: unacceptable content-type: text/html  text/plain
        //AFN默认只支持以下几种数据格式的解析 @"application/json", @"text/json", @"text/javascript"
        // AFN可上传
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //直接把AFN数据 全部转成NSData
        //不指定AFN类型 默认返回NSData数据
        // AFN.responseSerializer = AFHTTPResponseSerializer()
        
        //参数"_"表示忽略 参数自己命名 error信息一定要打印
        AFN.post(urlString, parameters: parameters, headers: nil, progress: { (progress) in
            
            
            }, success: { (_, result) in
                //将二进制数据转成 String
                //                let str = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
                
                
                print(result)
                //网络数据 可能是数组 字典  需要校验 进入分支的一定是字典
                if let dict = result as? [String :AnyObject]{
                    //开始字典转模型
                    let account = FYUserAccount(dict: dict)
                    
                    print(account)
                    //                    let access_token = dict[""] as? String
                    //                    let uid = dict[""] as? String
                    //                    //闭包中调用方法 要用方法加self
                    //                    //参数一定有值  强制解包
                    //                    self.loadUserInfo(access_token!, uid: uid!)
                    //类型相同的闭包  可以当做参数传递
                    //函数嵌套函数 闭包类型名字要一致
                    self.loadUserInfo(account: account, finished: finished)
                }
        }) { (_, error) in
            print(error)
        }
        
        
        
    }
    
    //请求用户信息 保存用户信息
    private func loadUserInfo(account : FYUserAccount,finished:@escaping(_ error:NSError?)->() ){
        let urlString = userURL
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.get(urlString, parameters: parmaters, headers: nil, progress: { (progress) in
            //
            }, success: { (_, result) in
                if let dict = result as?[String : AnyObject]{
                    // AnyObject对象妆花为字符串
                    account.avatar_large = dict["avatar_large"] as? String
                    account.name = dict["name"] as? String
                    account.saveAccount()
                    //执行闭包
                    finished(nil)
                }
        }) { (_, error) in
            //
            finished(error as NSError)
            print(error)
        }
        
    }
    
    
}
